package com.iwomy.envpro.platform.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.ArrayUtil;
import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.iwomy.envpro.admin.api.entity.SysTenant;
import com.iwomy.envpro.admin.api.feign.RemoteTenantService;
import com.iwomy.envpro.common.core.constant.SecurityConstants;
import com.iwomy.envpro.common.data.tenant.TenantContextHolder;
import com.iwomy.envpro.platform.dto.DeviceLogDTO;
import com.iwomy.envpro.platform.entity.DeviceLogEntity;
import com.iwomy.envpro.platform.mapper.DeviceLogMapper;
import com.iwomy.envpro.platform.service.DeviceLogService;
import com.iwomy.envpro.platform.utils.DataLimitUtil;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.time.LocalDateTime;

/**
 * 设备报文
 *
 * @author pig
 * @date 2023-10-19 16:07:20
 */
@Service
public class DeviceLogServiceImpl extends ServiceImpl<DeviceLogMapper, DeviceLogEntity> implements DeviceLogService {
	@Resource
	private RemoteTenantService remoteTenantService;

	@Override
	public Page getDeviceLogPage(Page page, DeviceLogDTO deviceLog) throws Exception {

		if(ObjectUtil.isEmpty(deviceLog.getEquipmentCode())){
			return page;
		}


		LambdaQueryWrapper<DeviceLogEntity> wrapper = Wrappers.lambdaQuery(BeanUtil.copyProperties(deviceLog, DeviceLogEntity.class));
		SysTenant tenant = remoteTenantService.details(TenantContextHolder.getTenantId(), SecurityConstants.FROM_IN).getData();
		if (ArrayUtil.isNotEmpty(deviceLog.getDateTime())) {

			wrapper.ge(DeviceLogEntity::getCreateTime, DataLimitUtil.judging(deviceLog.getDateTime()[0], tenant)).le(DeviceLogEntity::getCreateTime,
					DataLimitUtil.judging(deviceLog.getDateTime()[1], tenant));
		} else {
			wrapper.le(DeviceLogEntity::getCreateTime, LocalDateTime.now()).ge(DeviceLogEntity::getCreateTime,
					LocalDateTime.now().plusDays(-1*tenant.getDataPeriod()));
		}
		return this.page(page, wrapper);
	}
}